package org.jeecg.modules.wechat.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.demo.wechatauthorizer.entity.WechatAuthorizer;
import org.jeecg.modules.demo.wechatauthorizer.service.IWechatAuthorizerService;
import org.jeecg.modules.wechat.config.WechatThirdConfig;
import org.jeecg.modules.wechat.constant.WechatConstant;
import org.jeecg.modules.wechat.error.WechatErrorException;
import org.jeecg.modules.wechat.message.WechatThirdXmlMessage;
import org.jeecg.modules.wechat.service.RedisService;
import org.jeecg.modules.wechat.service.WechatNotifyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.jeecg.modules.wechat.util.crypto.SHA1;

/**
 * @author
 * @date 2018/12/6
 */
@Service
public class WechatNotifyServiceImpl implements WechatNotifyService {
    protected final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WechatThirdConfig wechatThirdConfig;
    @Autowired
    @Qualifier("redisWechatService")
    private RedisService redisService;
    @Autowired
    IWechatAuthorizerService wechatAuthorizerService;


    @Override
    public boolean checkSignature(String timestamp, String nonce, String signature) {
        try {
            return SHA1.gen(wechatThirdConfig.getComponentToken(), timestamp, nonce)
                    .equals(signature);
        } catch (Exception e) {
            this.log.error("Checking signature failed, and the reason is :" + e.getMessage());
            return false;
        }
    }


    @Override
    public String route(WechatThirdXmlMessage wechatThirdXmlMessage) throws WechatErrorException {
        if (wechatThirdXmlMessage == null) {
            throw new NullPointerException("message is empty");
        }
        if (StringUtils.equalsIgnoreCase(wechatThirdXmlMessage.getInfoType(), WechatConstant.COMPONENT_VERIFY_TICKET_KEY)) {
            log.info("COMPONENT_VERIFY_TICKET_KEY:"+wechatThirdXmlMessage.getComponentVerifyTicket());
            redisService.set(WechatConstant.COMPONENT_VERIFY_TICKET_KEY,wechatThirdXmlMessage.getComponentVerifyTicket(),600);
            return "success";
        }
        //停止授权
        else if (StringUtils.equals(wechatThirdXmlMessage.getInfoType(), "unauthorized")) {
            redisService.del(WechatConstant.AUTHORIZER_ACCESS_TOKEN_KEY+"_"+wechatThirdXmlMessage.getAuthorizerAppid(),WechatConstant.AUTHORIZER_REFRESH_TOKEN_KEY+"_"+wechatThirdXmlMessage.getAuthorizerAppid());
        }
        return "";
    }

}
